/*
 * @Author: windys
 * @Description: 
 * @Date: 2022-02-11 16:18:38
 */
import axios from 'axios'
import qs from 'qs'
import storage from "@/utils/storage.js";
import router from '@/router'
import AES from "@/utils/aes";
import { ElMessage } from 'element-plus'


const server = axios.create({
  // baseURL: import.meta.env.VITE_BASE_API,
  baseURL: 'https://app.caihuapp.com',
  withCredentials: true,
  timeout: 30000
})


let attach = JSON.stringify({
  system: window.navigator.platform,
  appName: window.navigator.appName,
  version: window.navigator.appVersion
})

server.interceptors.request.use(
  config => {
    config.headers['g-ver'] = 'V2.0.0'
    config.headers['attach'] = attach

    if (window.localStorage.getItem('teacher_user')) {
      config.headers['g-token'] = storage.getStorage('teacher_token')
      config.headers['g-ver'] = storage.getStorage('g-ver') || 'V3.2.0'
    }
    if (window.localStorage.getItem('teacher_user')) {
      if (config.method == 'get') {
        config.params.userId = storage.getStorage('teacher_user').userId
      }
      if (config.method == 'post' || config.method == 'put') {
        config.data.userId = storage.getStorage('teacher_user').userId
      }
    } else {
      if (config.method == 'get') {
        config.params.userId = 0
      }
      if (config.method == 'post') {
        config.data.userId = 0
      }
    }
    config.data = qs.stringify(config.data)
    return config
  },
  error => {
    console.log(error, '请求错误') // for debug
    Toast(error)
    return Promise.reject(error)
  }
)

server.interceptors.response.use(
  response => {
    console.log((response.headers.hasencodedjss), 'resresresres')
    // 加密结果
    var res;
    if (response.headers.hasencodedjss) {
      res = JSON.parse(AES.decrypt(response.data))
      console.log(res, '加密结果-------------')
    } else {
      // 非加密结果
      res = response.data
    }


    if (res.status === 0 || res.status === 8001) {
      return res.content
    } else if (res.status == 6001 || res.status == 5004) {
      // 登录失效
      ElMessage({
        message: res.msg,
        grouping: true,
        type: 'error',
      })
      window.localStorage.clear()
      window.close()
    } else if (res.status == 1011) {
      ElMessage({
        message: res.msg,
        grouping: true,
        type: 'error',
      })
    } else {
      ElMessage({
        message: res.msg,
        grouping: true,
        type: 'error',
      })
      return res.status
    }
  },
  error => {
    console.log('请求接口超时', error)
    return Promise.reject(error)
  }

)
export default server
